package joq.server;

import joq.*;
import java.io.IOException;
import java.nio.channels.ClosedChannelException;
import java.nio.channels.SocketChannel;
import java.nio.charset.Charset;

/**
 * Wraps the Request and Response functionality to simplify work for the
 * SocketServer.
 * @author jeff
 */
public class Transaction
{
    public enum STATUS { OPEN, CLOSED };

    private Request request;
    private Response response;
    private Charset charSet;
    private STATUS status;

    Transaction(Charset charSet, MessageQueue queue)
    {
	this.charSet = charSet;
	request = new Request(charSet);
	response = new Response(request, charSet);
	status = STATUS.OPEN;
    }

    public STATUS getStatus()
    {
	return status;
    }

    public boolean receive(SocketChannel client) throws IOException, ProtocolError
    {
	try {
	    return request.read(client);
	} catch (ClosedChannelException e) {
	    status = STATUS.CLOSED;
	    return true;
	}
    }

    public void send(SocketChannel client) throws IOException
    {
	response.write(client);
    }

    public Message getMessage()
    {
	return request.getMessage();
    }
}
